# -*- coding: utf-8 -*-
import os
from django.contrib import messages
from django.shortcuts import render
from django.http.response import HttpResponseRedirect, HttpResponse,\
    StreamingHttpResponse
from django.contrib.auth.decorators import login_required
from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt
 
from mysite.settings import BASE_DIR  #本地运行时 BASE_DIR = /Users/wuchunlong/local/upgit/Menu-Bootstrap3/mysite
from myAPI.fileAPI import upfile_save

IMG_PATH_STATIC_COMMON = os.path.join(BASE_DIR, 'static_common', 'upfile')  # 本地运行时，显示图像文件目录
UPFILENAME = "upfilename.jpg" #保存在服务器上的文件名


imgExt = ['.bmp', '.gif', '.jpg', '.pic', '.png', '.tif', '.jpeg', '.php',\
          '.BMP', '.GIF', '.JPG', '.PIC', '.PNG', '.TIF', '.JPEG', '.PHP']


###不收费  使用 CnOcr  从图片中获得文字
# https://github.com/breezedeus/cnocr
# pip3 install cnocr -i https://mirrors.aliyun.com/pypi/simple/
# $ cnocr --help# 缺点：所有参数都使用默认值，对有些图片识别的准确率不高。使用 det_model_name='naive_det' 的最大优势是速度快，劣势是对图片比较挑剔。
# 支持在线运行
from cnocr import CnOcr
def cnOcr_imgToStr(filename, model_name):
    ''' 图像文件转换文字  '''
    s = ''
    try: 
        if  model_name == 'naive_det':  
            ocr = CnOcr(det_model_name='naive_det')
        else:
            ocr = CnOcr() # 所有参数都使用默认值
        items = ocr.ocr(filename) #filename图像文件
        items = [i["text"]+"\n"  for i in  items]
        s =''.join(items)
    except Exception as ex:
        s = str(ex)
    return s

def index(request):           
    return render(request, 'mobile-phone/index.html', context=locals()) 

def imgtotext(request): # 图片转换文本 
    if request.method == "POST":   
        upfile = request.FILES.get("upfile", None)  
        if not upfile:
            messages.info(request, '没有选择上传文件！')  
            return HttpResponseRedirect('/')
        #print(is_upfile_save(upfile))
        name = upfile_save(IMG_PATH_STATIC_COMMON, upfile, UPFILENAME)
        if "Error" in name:
            s = ""
            messages.info(request, "上传图片文件失败!\n %s."%name)
        else:
            messages.info(request, "上传图片文件成功!\n %s. \n 图片转换文本内容如下："%name)
            s = cnOcr_imgToStr(os.path.join(IMG_PATH_STATIC_COMMON, UPFILENAME), "")
        return render(request, 'mobile-phone/showtext.html', context=locals()) 
    return render(request, 'mobile-phone/upfile.html', context=locals()) 

def img(request):           
    return render(request, 'mobile-phone/img.html', context=locals()) 

def table(request):           
    return render(request, 'mobile-phone/table.html', context=locals()) 

def more(request):           
    return render(request, 'base_more.html', context=locals()) #更多

def bar_chart(request):            
    return render(request, 'mobile-phone/bar_chart.html', context=locals()) 

def bar_chart2(request):            
    return render(request, 'mobile-phone/bar_chart2.html', context=locals()) 


# android手机应用程序客户端使用
@csrf_exempt 
def upload(request):
    '''android手机按钮（上传文件） 图像识别文字  ''' 
    mag = "欢迎使用"
    if request.method == "POST":
        upFile = request.FILES.get("upfile","")
        if not upFile:
            print("Open File Error.")  
            return HttpResponse("Open File Error.")  
        name = upFile.name;         
        if os.path.splitext(name)[1] not in imgExt:
               print("Open IMG Error.")
               return HttpResponse("Open IMG Error.")
        filename = "%s/upfile/%s"%(os.path.abspath(os.path.dirname(__file__)), name)
        f = open(filename, 'wb+') 
        for chunk in upFile.chunks():
            f.write(chunk)  
        f.close()
        print("upfile Seccess.")
        #s = getimgstr(filename) #百度收费
        s = cnOcr_imgToStr(filename, '')
        print("img to str Seccess.")
        return HttpResponse(s)       
    return HttpResponse(mag)


@csrf_exempt 
def imgtostr(request):
    '''android手机按钮（上传转换） 图像识别文字  ''' 
    mag = "欢迎使用"
    if request.method == "POST":
        upFile = request.FILES.get("upfile","")
        if not upFile:
            print("Open File Error.")  
            return HttpResponse("Open File Error.")  
        name = upFile.name;         
        if os.path.splitext(name)[1] not in imgExt:
               print("Open IMG Error.")
               return HttpResponse("Open IMG Error.")
        filename = "%s/upfile/%s"%(os.path.abspath(os.path.dirname(__file__)), name)
        f = open(filename, 'wb+') 
        for chunk in upFile.chunks():
            f.write(chunk)  
        f.close()
        print("upfile Seccess.")
        #s = getimgstr(filename) #百度收费
        s = cnOcr_imgToStr(filename, 'naive_det')
        print("img to str Seccess.")
        return HttpResponse(s)       
    return HttpResponse(mag)




   